from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import WriteRowsEvent
import pymysql
from pymysql import OperationalError, ProgrammingError

mysql_settings = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "passwd": "123"  # 确保密码正确
}

try:
    # 先测试基础连接是否正常
    conn = pymysql.connect(**mysql_settings)
    print("MySQL 连接成功！")
    conn.close()

    # 启动监听
    stream = BinLogStreamReader(
        connection_settings=mysql_settings,
        server_id=1,  # 必须与 MySQL 配置的 server-id 一致
        only_events=[WriteRowsEvent],
        # 增加调试参数，打印更多信息
        log_file='',  # 从最新的 binlog 开始监听
        log_pos=4,
        resume_stream=True
    )
    print("binlog 监听已启动，等待事件...")

    for event in stream:
        print("\n捕获到插入事件：")
        print(f"数据库：{event.schema}")
        print(f"表名：{event.table}")
        for row in event.rows:
            print(f"插入的数据：{row['values']}")

except OperationalError as e:
    print(f"连接错误：{e}（可能是主机、端口、密码错误）")
except ProgrammingError as e:
    print(f"权限错误：{e}（可能缺少 REPLICATION 权限）")
except Exception as e:
    print(f"其他错误：{e}")
except KeyboardInterrupt:
    print("\n停止监听")
finally:
    if 'stream' in locals():
        stream.close()